package aerouacmsla.interfazDeUsuario;
import aerouacmsla.entidad.Avion;
import aerouacmsla.procedimientos.BDConexion;
import aerouacmsla.procedimientos.CreateTables;
import aerouacmsla.procedimientos.GeneradorIdes;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

/**
 *
 * @author six-14
 */
public class VentanaNuevoAvion extends javax.swing.JDialog {

    private BDConexion miConexion;
    private CreateTables modeloTabla = new CreateTables();
    private Avion avionActual = new Avion();

    public VentanaNuevoAvion() {
        initComponents();
    }

    public VentanaNuevoAvion(BDConexion miConexion) {
        initComponents();
        setMiConexion(miConexion);
        setModal(true);

        getMiConexion().sendSQLQuery("SELECT nombre_estado FROM estado");
        estadoRegistroAvion.setModel(new DefaultComboBoxModel(getMiConexion().getLastResultSetColumnStrings("nombre_estado")));

    }

    public VentanaNuevoAvion(Avion a, BDConexion miConexion) {
        initComponents();
        setMiConexion(miConexion);
         setAvionActual(a);
        setModal(true);

         getMiConexion().sendSQLQuery("SELECT nombre_estado FROM estado");
        estadoRegistroAvion.setModel(new DefaultComboBoxModel(getMiConexion().getLastResultSetColumnStrings("nombre_estado")));
       Registrar.setText("Modificar");
       marcaRegistroAvion.setText(getAvionActual().getMarca());
       modeloRegistroAvion.setText(getAvionActual().getModelo());
       serieRegistroAvion.setText(getAvionActual().getSerieAvion());
       asientosRegistroAvion.setText(getAvionActual().getNumeroAsientos() + "");
       campoUbicacion.setText(getAvionActual().getUbicacion());
    }

    public BDConexion getMiConexion() {
        return miConexion;
    }

    public void setMiConexion(BDConexion miConexion) {
        this.miConexion = miConexion;
    }

    public Avion getAvionActual() {
        return avionActual;
    }

    public void setAvionActual(Avion avionActual) {
        this.avionActual = avionActual;
    }



    public boolean validarTam (String cadena, int tamano){
        if(cadena.length()<=tamano){
            return false;
        }
        return true;
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        topPanel = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        idRegistroAvion = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        estadoRegistroAvion = new javax.swing.JComboBox();
        asientosRegistroAvion = new javax.swing.JTextField();
        Registrar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        modeloRegistroAvion = new javax.swing.JTextField();
        marcaRegistroAvion = new javax.swing.JTextField();
        serieRegistroAvion = new javax.swing.JTextField();
        campoUbicacion = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Avion");
        setIconImage(new ImageIcon(getClass().getResource("/Recursos/Icono32px.png")).getImage());

        topPanel.setBackground(new java.awt.Color(51, 51, 51));

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18));
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("Panel Registro de Aviones");

        javax.swing.GroupLayout topPanelLayout = new javax.swing.GroupLayout(topPanel);
        topPanel.setLayout(topPanelLayout);
        topPanelLayout.setHorizontalGroup(
            topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(topPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addContainerGap(327, Short.MAX_VALUE))
        );
        topPanelLayout.setVerticalGroup(
            topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(topPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addContainerGap(31, Short.MAX_VALUE))
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos Obligatorios"));

        jLabel1.setText("Id Avion:");

        jLabel4.setText("Numero de Asientos:");

        jLabel5.setText("Estado del Avion:");

        estadoRegistroAvion.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Disponible", "Vuelo", "Reparacion" }));

        Registrar.setText("Registrar");
        Registrar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                RegistrarMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(37, 37, 37)
                        .addComponent(idRegistroAvion))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(asientosRegistroAvion))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addGap(18, 18, 18)
                        .addComponent(estadoRegistroAvion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(14, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(66, Short.MAX_VALUE)
                .addComponent(Registrar)
                .addGap(62, 62, 62))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(idRegistroAvion))
                .addGap(42, 42, 42)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(asientosRegistroAvion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(31, 31, 31)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(estadoRegistroAvion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(50, 50, 50)
                .addComponent(Registrar)
                .addContainerGap(58, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos no Obligatorios"));

        jLabel6.setText("Modelo:");

        jLabel7.setText("Marca:");

        jLabel8.setText("Serie:");

        campoUbicacion.setEditable(false);

        jLabel2.setText("Ubicacion");

        jButton1.setText("...");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel6)
                        .addComponent(jLabel7)
                        .addComponent(jLabel8))
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(campoUbicacion, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(modeloRegistroAvion, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE)
                    .addComponent(marcaRegistroAvion, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(serieRegistroAvion, javax.swing.GroupLayout.Alignment.LEADING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(23, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(modeloRegistroAvion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(31, 31, 31)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(marcaRegistroAvion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(44, 44, 44)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(serieRegistroAvion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campoUbicacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(jButton1))
                .addContainerGap(82, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(topPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(topPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void RegistrarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_RegistrarMouseClicked


        if(!asientosRegistroAvion.getText().isEmpty()

          ){

              boolean excedecaracteres[] = {
                  validarTam(asientosRegistroAvion.getText(),5),
                  validarTam(modeloRegistroAvion.getText(),15),
                  validarTam(marcaRegistroAvion.getText(),15),
                  validarTam(serieRegistroAvion.getText(),18)

              };

              if( excedecaracteres[0] || excedecaracteres[1] ||
                  excedecaracteres[2] || excedecaracteres[3] ){

                  boolean someError = false;
            String mensajeDeError = "";

            if (excedecaracteres[0]){
                someError = true;
                mensajeDeError += "El campo 'Numero De Asientos' debe ser menor o igual a 5 caracteres\n";
            System.out.println("exede numero de caracteres en Numero De Asientos");}

            if (excedecaracteres[1]){
                someError = true;
                mensajeDeError += "El campo 'Modelo' debe ser menor o igual a 15 caracteres\n";
            System.out.println("exede numero de caracteres en Modelo");}

            if (excedecaracteres[2]){
                someError = true;
                mensajeDeError += "El campo 'Marca' debe ser menor o igual a 15 caracteres\n";
            System.out.println("exede numero de caracteres en Marca");}

            if (excedecaracteres[3]){
                someError = true;
                mensajeDeError += "El campo 'Serie' debe ser menor o igual a 12 caracteres\n";
            System.out.println("exede numero de caracteres en Serie");}

              if (someError)
                JOptionPane.showMessageDialog(this,
                 mensajeDeError,
                 "Error de datos",
                 JOptionPane.ERROR_MESSAGE);



              }else{
                  int asiento = Integer.parseInt(asientosRegistroAvion.getText());

                  getAvionActual().setNumeroAsientos(asiento);
                  getAvionActual().setMarca(marcaRegistroAvion.getText());
                  getAvionActual().setModelo(modeloRegistroAvion.getText());
                  getAvionActual().setSerieAvion(serieRegistroAvion.getText());
                  getAvionActual().setUbicacion(campoUbicacion.getText());

                  if(Registrar.getText().equalsIgnoreCase("Registrar"))
                  getAvionActual().setId(0);

                  String estado = estadoRegistroAvion.getSelectedItem().toString();

                getMiConexion().sendSQLQuery("SELECT id_estado FROM estado WHERE nombre_estado ='" + estado + "';");
                try {
                    if (getMiConexion().getResultado().next()) {
                        int idestado = getMiConexion().getResultado().getInt("id_estado");
                        getAvionActual().setEstado(idestado);
                    }
                } catch (SQLException ex) {
                    Logger.getLogger(VentanaNuevoAvion.class.getName()).log(Level.SEVERE, null, ex);
                }


                  //getAvionActual().setEstado(
                  //        estadoRegistroAvion.getSelectedIndex());

                  /* GeneradorIdes GI = new GeneradorIdes(getAvionActual().getMarca(), getAvionActual().getModelo(), getAvionActual().getSerieAvion());
                  if (Registrar.getText().equalsIgnoreCase("Registrar")) {
                      avionActual.setId(Integer.parseInt(GI.getId()));
                      for (;;) {
                          try {
                              if (getMiConexion().sendSQLQuery("SELECT * FROM avion WHERE id_avion = '" + getAvionActual().getId() + "';").next()) {
                                  avionActual.setId(Integer.parseInt(GI.siguienteId()));
                              } else {
                                  break;
                              }
                          } catch (SQLException ex) {
                              Logger.getLogger(PanelAdministrarCiudades.class.getName()).log(Level.SEVERE, null, ex);
                          }
                      }
                  }
*/



            String SQL = null;
            if(Registrar.getText().equalsIgnoreCase("Registrar")){
                SQL = "INSERT INTO avion VALUES ( null , '"+getAvionActual().getNumeroAsientos() +"','"+getAvionActual().getModelo() +"', '" +
                        getAvionActual().getMarca() +"' , '"+getAvionActual().getSerieAvion() +"', "+getAvionActual().getEstado()+",'" + avionActual.getUbicacion() +"');";
            }
            else{
                SQL = " UPDATE avion SET marca = '" +
                        getAvionActual().getMarca() +"' ,numero_asientos="+getAvionActual().getNumeroAsientos()+", modelo ='"+getAvionActual().getModelo() +"',serie = '" +
                        getAvionActual().getSerieAvion()+"',id_estado = " +getAvionActual().getEstado()+", ubicacion='" + getAvionActual().getUbicacion() + "' WHERE id_avion =" + getAvionActual().getId()+";";
                
            
                  }

            getMiConexion().sendSQL(SQL);
            if(Registrar.getText().equalsIgnoreCase("Registrar")){JOptionPane.showMessageDialog(this,
                 "El avion ha sido registrado exitosamente",
                 "Avion Registrado Exitosamente",
                 JOptionPane.INFORMATION_MESSAGE);
            this.dispose();

                  }else{JOptionPane.showMessageDialog(this,
                 "El avion ha sido modificado exitosamente",
                 "Avion Registrado Exitosamente",
                 JOptionPane.INFORMATION_MESSAGE);
                  this.dispose();}
              }

             }else JOptionPane.showMessageDialog(this,
                 "Es necesario llenar todos los campos obligatorios",
                 "Error de datos",
                 JOptionPane.ERROR_MESSAGE);        

    }//GEN-LAST:event_RegistrarMouseClicked

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
        DialogoCiudades SeleccionUbicacion = new DialogoCiudades(getMiConexion());
        SeleccionUbicacion.setVisible(true);
        campoUbicacion.setText(SeleccionUbicacion.getId());
    }//GEN-LAST:event_jButton1MouseClicked

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VentanaNuevoAvion().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Registrar;
    private javax.swing.JTextField asientosRegistroAvion;
    private javax.swing.JTextField campoUbicacion;
    private javax.swing.JComboBox estadoRegistroAvion;
    private javax.swing.JLabel idRegistroAvion;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField marcaRegistroAvion;
    private javax.swing.JTextField modeloRegistroAvion;
    private javax.swing.JTextField serieRegistroAvion;
    private javax.swing.JPanel topPanel;
    // End of variables declaration//GEN-END:variables

}
